#!/usr/bin/env python3
# coding=utf-8
# @time:2023-04-12 15:51
# Author:TongChunWang
# @File:clone_vmware.py
# @Software:PyCharm

import json
import os
import pprint
import string
import sys
import time
import yaml
import ansible_runner
from pyVmomi import vim, vmodl
from pyVim.connect import SmartConnect

# 脚本入参
vc_host = ''  # vCenter地址
vc_username = ''  # vCenter用户
vc_password = ''  # vCenter密码
in_parameter = '''
[{"type":"vCenter","name":"tong-create-vm-test-0012","ip_and_port_group":[{"ip":"192.168.60.222","mask":"255.255.255.0","gateway":"192.168.60.1","dns1":"192.168.60.1","networks_type":"vmxnet3","networks_name":"DPortGroup 60"},{"ip":"192.168.60.224","mask":"255.255.255.0","gateway":"192.168.60.1","dns1":"192.168.60.1","networks_type":"vmxnet3","networks_name":"DPortGroup 60"}],"cpu_cores":2,"cpu_sockets":1,"mem_sizeGB":2,"create_disk":[{"disk_sizeGB":50},{"disk_sizeGB":50}],"datacenter":"Datacenter","esxi_host":"10.11.197.56","datastore":"197.56","guest_template":"60.143-centos7.9-base-vm-create","resource_pool":"","templateHosts":["Host_Linux_Base_SncAgentScript"]}]
'''
vm_template_root_pwd = ""
agent_user = ""
agent_user_pwd = ""
proxy_name = "192.168.32.15:10033"
wait_vm_start_time = 60
agent_cf_agent_ip = "192.168.7.2"
agent_cf_proxy_ip = "192.168.32.19"
agent_cf_zabbix_ip = "192.168.32.15"
# 脚本入参结束

# 脚本出参
join_result = ""
create_status = ""


# 脚本出参结束


def add_proxy(init_json):
    out_list = list()
    init_obj = json.loads(init_json)
    for vm_info in init_obj:
        if not vm_info.get("proxyName"):
            vm_info["proxyName"] = proxy_name

        out_list.append(vm_info)

    return json.dumps(out_list)


def yaml_write(configfile, config_dic):
    with open(configfile, "w", encoding='utf-8') as file:
        yaml.dump(config_dic, file, default_flow_style=False, allow_unicode=True, explicit_start=True, sort_keys=False)


def yaml_read(configfile):
    with open(configfile, "r", encoding='utf-8') as file:
        config_dic = yaml.safe_load(file)
    return config_dic


def json_read(configfile):
    with open(configfile, "r", encoding='utf-8') as file:
        config_dic = json.load(file)
    return config_dic


def init_yaml_template(temp_path, file_name, run_type):
    if not os.path.exists(temp_path):
        os.makedirs(temp_path)
    config_file = "{0}/{1}".format(temp_path, file_name)
    yaml_def_data = []
    # 文件是否存在，都会替换yml内容
    if "clone" in run_type:
        yaml_def_temp = [
            {'name': 'vmware facts from vCenter', 'hosts': 'localhost', 'gather_facts': False, 'connection': 'local',
             'vars': {'vc_host': '192.168.1.1', 'vc_username': 'administrator@vcenter.one',
                      'vc_password': '123456', 'vc_datacenter': 'Datacenter',
                      'vc_guest_name': 'tong-ansible-test-create-vm-04', 'vc_esxi_host': '10.11.197.17',
                      'vc_guest_folder': '/', 'vc_guest_template': 'Centos7.9-template-lzp',
                      'vc_networks_name': 'DPortGroup 60', 'vc_networks_type': 'vmxnet3', 'vc_resource_pool': '',
                      'vc_datastore': '100.84', 'vc_guest_hd': '30', 'vc_cpu_cores': 2, 'vc_cpu_sockets': 1,
                      'vc_guest_mem_mb': 2048, 'vc_guest_ip': '192.168.60.147', 'vc_guest_mask': '255.255.255.0',
                      'vc_guest_gateway': '192.168.60.1', 'dns1': '192.168.60.1'},
             'tasks': [{'name': 'Start Clone VM instance', 'debug': 'msg="please wait..."'},
                       {'name': 'Create a virtual machine on given ESXi hostname',
                        'vmware_guest': {'hostname': '{{ vc_host }}', 'username': '{{ vc_username }}',
                                         'password': '{{ vc_password }}', 'validate_certs': False,
                                         'folder': '{{ vc_guest_folder }}', 'datacenter': '{{ vc_datacenter }}',
                                         'name': '{{ vc_guest_name }}', 'state': 'poweredon',
                                         'esxi_hostname': '{{ vc_esxi_host }}', 'template': '{{ vc_guest_template }}',
                                         'resource_pool': '{{ vc_resource_pool }}', 'disk': [
                                {'size_gb': '{{ vc_guest_hd }}', 'type': 'eagerzeroedthick',
                                 'datastore': '{{ vc_datastore }}'},
                                {'size_gb': 100, 'type': 'eagerzeroedthick', 'datastore': '{{ vc_datastore }}'}],
                                         'hardware': {'memory_mb': '{{ vc_guest_mem_mb }}',
                                                      'num_cpus': '{{ vc_cpu_cores }}',
                                                      'num_cpu_cores_per_socket': '{{ vc_cpu_sockets }}',
                                                      'hotadd_cpu': True, 'hotadd_memory': True, 'scsi': 'lsilogic'},
                                         'networks': [{'name': '{{ vc_networks_name }}', 'ip': '{{ vc_guest_ip }}',
                                                       'netmask': '{{ vc_guest_mask }}',
                                                       'gateway': '{{ vc_guest_gateway }}',
                                                       'device_type': '{{ vc_networks_type }}',
                                                       'dvswitch_name': 'DSwitch', 'connected': True,
                                                       'start_connected': True, 'type': 'static'}],
                                         'customization': {'dns_servers': ['{{ dns1 }}']}}, 'delegate_to': 'localhost',
                        'register': 'deploy_vm'}, {'name': 'Wait for vm started', 'pause': {'seconds': "$wait_vm"}},
                       {'name': 'Get vm info',
                        'vmware_guest_facts': {'hostname': '{{ vc_host }}', 'username': '{{ vc_username }}',
                                               'password': '{{ vc_password }}', 'datacenter': '{{ vc_datacenter }}',
                                               'validate_certs': False, 'name': '{{ vc_guest_name }}'},
                        'delegate_to': 'localhost', 'register': 'vm_result'},
                       {'local_action': 'copy content={{ vm_result }} dest=/tmp/.ansible_vmware/vm_cache.json'}]}]

        yaml_def_data_template = string.Template(json.dumps(yaml_def_temp))

        yaml_def_data = json.loads(yaml_def_data_template.safe_substitute(wait_vm=wait_vm_start_time))

    elif "ip" in run_type:
        yaml_def_temp = [
            {'name': 'vmware facts from vCenter', 'hosts': 'localhost', 'gather_facts': False, 'connection': 'local',
             'vars': {'vc_host': '192.168.1.1', 'vc_username': 'administrator@vcenter.one',
                      'vc_password': '123456', 'vm_name': 'tong-create-vm-test-03',
                      'vm_hostname': 'tong-create-vm-test-03', 'vm_folder': '/', 'vc_datacenter': 'Datacenter',
                      'ip1': '192.168.60.222', 'ga1': '192.168.60.1', 'dns1': '192.168.60.1',
                      'vc_guest_ip': '192.168.60.147', 'vc_proxy_ip': '192.168.60.147'}, 'tasks': [
                {'name': 'add permission on Linux',
                 'vmware_vm_shell': {'vm_id': '{{ vm_name }}', 'hostname': '{{ vc_host }}',
                                     'username': '{{ vc_username }}', 'password': '{{ vc_password }}',
                                     'vm_username': 'root', 'vm_password': '$vm_password', 'validate_certs': 'false',
                                     'vm_shell': '/usr/bin/chmod', 'vm_shell_args': '+x /root/network-init.sh',
                                     'vm_shell_cwd': '/root/'}}, {'name': 'Set IP Address on Linux',
                                                                  'vmware_vm_shell': {'vm_id': '{{ vm_name }}',
                                                                                      'hostname': '{{ vc_host }}',
                                                                                      'username': '{{ vc_username }}',
                                                                                      'password': '{{ vc_password }}',
                                                                                      'vm_username': 'root',
                                                                                      'vm_password': '$vm_password',
                                                                                      'validate_certs': 'false',
                                                                                      'vm_shell': '/usr/bin/bash',
                                                                                      'vm_shell_args': "/root/network-init.sh '{{ ip1 }}' '{{ ga1 }}' '{{ dns1 }}' '{{ ip2 }}' '{{ ga2 }}' '{{ dns2 }}'",
                                                                                      'vm_shell_cwd': '/root/'}},
                {'name': 'Update Agent IP Address',
                 'vmware_vm_shell': {'vm_id': '{{ vm_name }}', 'hostname': '{{ vc_host }}',
                                     'username': '{{ vc_username }}', 'password': '{{ vc_password }}',
                                     'vm_username': 'root', 'vm_password': '$vm_password', 'validate_certs': 'false',
                                     'vm_shell': '/usr/bin/sed',
                                     'vm_shell_args': "-i '/^agent.ip=/s/$agentip/'{{ vc_guest_ip }}'/' config.properties",
                                     'vm_shell_cwd': '/home/shsnc/snc_agent/config/'}},
                {'name': 'Update Agent proxy IP Address 1',
                 'vmware_vm_shell': {'vm_id': '{{ vm_name }}', 'hostname': '{{ vc_host }}',
                                     'username': '{{ vc_username }}', 'password': '{{ vc_password }}',
                                     'vm_username': 'root', 'vm_password': '$vm_password', 'validate_certs': 'false',
                                     'vm_shell': '/usr/bin/sed',
                                     'vm_shell_args': "-i '/^agent.proxy.ip=/s/$proxyip/'{{ vc_proxy_ip }}'/' config.properties",
                                     'vm_shell_cwd': '/home/shsnc/snc_agent/config/'}},
                {'name': 'Update Agent proxy IP Address 2',
                 'vmware_vm_shell': {'vm_id': '{{ vm_name }}', 'hostname': '{{ vc_host }}',
                                     'username': '{{ vc_username }}', 'password': '{{ vc_password }}',
                                     'vm_username': 'root', 'vm_password': '$vm_password', 'validate_certs': 'false',
                                     'vm_shell': '/usr/bin/sed',
                                     'vm_shell_args': "-i '/^agent.monitor.zabbix.serverIp=/s/$zabbixip/'{{ vc_proxy_ip }}'/' config.properties",
                                     'vm_shell_cwd': '/home/shsnc/snc_agent/config/'}}, {'name': 'config Agent Start',
                                                                                         'vmware_vm_shell': {
                                                                                             'vm_id': '{{ vm_name }}',
                                                                                             'hostname': '{{ vc_host }}',
                                                                                             'username': '{{ vc_username }}',
                                                                                             'password': '{{ vc_password }}',
                                                                                             'vm_username': '$agentuser',
                                                                                             'vm_password': '$agentpwd',
                                                                                             'validate_certs': 'false',
                                                                                             'vm_shell': '/usr/bin/sed',
                                                                                             'vm_shell_args': "-i '$a\\agent.protect.task.enable=true' config.properties",
                                                                                             'vm_shell_cwd': '/home/shsnc/snc_agent/config/'}},
                {'name': 'Start Agent', 'vmware_vm_shell': {'vm_id': '{{ vm_name }}', 'hostname': '{{ vc_host }}',
                                                            'username': '{{ vc_username }}',
                                                            'password': '{{ vc_password }}',
                                                            'vm_username': '$agentuser',
                                                            'vm_password': '$agentpwd', 'validate_certs': 'false',
                                                            'vm_shell': '/usr/bin/bash',
                                                            'vm_shell_args': 'snc_agent_service.sh start',
                                                            'vm_shell_cwd': '/home/shsnc/snc_agent/'}},
                {'name': 'Config Hostname 01',
                 'vmware_vm_shell': {'vm_id': '{{ vm_name }}', 'hostname': '{{ vc_host }}',
                                     'username': '{{ vc_username }}', 'password': '{{ vc_password }}',
                                     'vm_username': 'root', 'vm_password': '$vm_password', 'validate_certs': 'false',
                                     'vm_shell': '/usr/bin/sed', 'vm_shell_args': "-i '$a\\{{ vm_hostname }}' hostname",
                                     'vm_shell_cwd': '/etc/'}}, {'name': 'Config Hostname 02',
                                                                 'vmware_vm_shell': {'vm_id': '{{ vm_name }}',
                                                                                     'hostname': '{{ vc_host }}',
                                                                                     'username': '{{ vc_username }}',
                                                                                     'password': '{{ vc_password }}',
                                                                                     'vm_username': 'root',
                                                                                     'vm_password': '$vm_password',
                                                                                     'validate_certs': 'false',
                                                                                     'vm_shell': '/usr/bin/hostnamectl',
                                                                                     'vm_shell_args': "set-hostname '{{ vm_hostname }}'",
                                                                                     'vm_shell_cwd': '/root/'}},
                {'name': 'Disable Root Login 01',
                 'vmware_vm_shell': {'vm_id': '{{ vm_name }}', 'hostname': '{{ vc_host }}',
                                     'username': '{{ vc_username }}', 'password': '{{ vc_password }}',
                                     'vm_username': 'root', 'vm_password': '$vm_password', 'validate_certs': 'false',
                                     'vm_shell': '/usr/bin/sed',
                                     'vm_shell_args': "-i '/PermitRootLogin/s/yes/no/' sshd_config",
                                     'vm_shell_cwd': '/etc/ssh/'}}, {'name': 'Disable Root Login 02',
                                                                     'vmware_vm_shell': {'vm_id': '{{ vm_name }}',
                                                                                         'hostname': '{{ vc_host }}',
                                                                                         'username': '{{ vc_username }}',
                                                                                         'password': '{{ vc_password }}',
                                                                                         'vm_username': 'root',
                                                                                         'vm_password': '$vm_password',
                                                                                         'validate_certs': 'false',
                                                                                         'vm_shell': '/usr/bin/systemctl',
                                                                                         'vm_shell_args': 'restart sshd',
                                                                                         'vm_shell_cwd': '/root/'}}]}]

        yaml_def_data_template = string.Template(json.dumps(yaml_def_temp))

        yaml_def_data = json.loads(
            yaml_def_data_template.safe_substitute(vm_password=vm_template_root_pwd, agentip=agent_cf_agent_ip,
                                                   proxyip=agent_cf_proxy_ip, zabbixip=agent_cf_zabbix_ip,
                                                   agentuser=agent_user, agentpwd=agent_user_pwd))
    else:
        exit("type error")
    yaml_write(config_file, yaml_def_data)


def update_clone_vm_yaml_data(temp_path, file_name, in_vars):
    config_file = "{0}/{1}".format(temp_path, file_name)
    clone_vm = yaml_read(config_file)
    clone_vm_vars = clone_vm[0]["vars"]
    # ---------------------------------# 云主机磁盘(GB)
    del clone_vm[0]["tasks"][1]["vmware_guest"]["disk"]
    disk_list = []
    for disk in in_vars["create_disk"]:
        disk_list.append({'datastore': '{{ vc_datastore }}', 'size_gb': disk["disk_sizeGB"], 'type': 'thin'})
        # type 值 eagerzeroedthick 表示厚置备置零，在创建时为虚拟磁盘分配所需的空间。
        # type 值 thin 表示精简磁盘，创建速度快
    clone_vm[0]["tasks"][1]["vmware_guest"]["disk"] = disk_list
    # --------------------------------- 配置网卡
    del clone_vm[0]["tasks"][1]["vmware_guest"]["networks"]
    networks_list = []
    for ip in in_vars["ip_and_port_group"]:
        networks_template = {'name': ip["networks_name"], 'ip': ip["ip"], 'netmask': '255.255.255.0',
                             'gateway': '192.168.60.1', 'device_type': ip["networks_type"], 'dvswitch_name': 'DSwitch',
                             'connected': True, 'start_connected': True, 'type': 'static'}
        networks_list.append(networks_template)
    clone_vm[0]["tasks"][1]["vmware_guest"]["networks"] = networks_list
    # --------------------------------- 其他
    clone_vm_vars["vc_cpu_cores"] = in_vars["cpu_cores"]
    clone_vm_vars["vc_cpu_sockets"] = in_vars["cpu_sockets"]
    clone_vm_vars["vc_guest_mem_mb"] = int(in_vars["mem_sizeGB"]) * 1024
    clone_vm_vars["vc_guest_name"] = "{0}_{1}".format(in_vars["name"], filter_ip(in_vars["ip_and_port_group"]))
    clone_vm_vars["vc_datacenter"] = in_vars["datacenter"]
    clone_vm_vars["vc_esxi_host"] = in_vars["esxi_host"]
    clone_vm_vars["vc_datastore"] = in_vars["datastore"]

    # clone_vm_vars["vc_guest_gateway"] = in_vars["guest_gateway"]
    # clone_vm_vars["vc_guest_mask"] = in_vars["guest_mask"]
    # clone_vm_vars["dns1"] = in_vars["dns1"]
    # clone_vm_vars["vc_guest_folder"] = in_vars["guest_folder"]

    clone_vm_vars["vc_resource_pool"] = in_vars["resource_pool"]
    clone_vm_vars["vc_guest_template"] = in_vars["guest_template"]
    # ---------------------------------
    clone_vm_vars["vc_host"] = vc_host
    clone_vm_vars["vc_username"] = vc_username
    clone_vm_vars["vc_password"] = vc_password
    yaml_write(config_file, clone_vm)


def update_ip_yaml_data(temp_path, file_name, in_vars):
    config_file = "{0}/{1}".format(temp_path, file_name)
    clone_vm = yaml_read(config_file)
    clone_vm_vars = clone_vm[0]["vars"]
    # --------------------------------- 配置网卡
    ip_port_all = "/root/network-init.sh"
    for ip in in_vars["ip_and_port_group"]:
        dns = 0 if len(ip["dns1"]) == 0 else ip["dns1"]
        ip_port_all += " {0} {1} {2}".format(ip["ip"], ip["gateway"], dns)
    clone_vm[0]["tasks"][1]["vmware_vm_shell"]["vm_shell_args"] = ip_port_all
    # ---------------------------------
    clone_vm_vars["vc_host"] = vc_host
    clone_vm_vars["vc_username"] = vc_username
    clone_vm_vars["vc_password"] = vc_password
    clone_vm_vars["vc_guest_ip"] = filter_ip(in_vars["ip_and_port_group"])
    clone_vm_vars["vc_proxy_ip"] = in_vars["proxyName"].split(":")[0]
    clone_vm_vars["vm_name"] = "{0}_{1}".format(in_vars["name"], filter_ip(in_vars["ip_and_port_group"]))
    clone_vm_vars["vm_hostname"] = in_vars["name"]
    yaml_write(config_file, clone_vm)


def wait_for_tasks(si, tasks):
    property_collector = si.content.propertyCollector
    task_list = [str(task) for task in tasks]
    # Create filter
    obj_specs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task)
                 for task in tasks]
    property_spec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task,
                                                               pathSet=[],
                                                               all=True)
    filter_spec = vmodl.query.PropertyCollector.FilterSpec()
    filter_spec.objectSet = obj_specs
    filter_spec.propSet = [property_spec]
    pcfilter = property_collector.CreateFilter(filter_spec, True)
    try:
        version, state = None, None
        # Loop looking for updates till the state moves to a completed state.
        while task_list:
            update = property_collector.WaitForUpdates(version)
            for filter_set in update.filterSet:
                for obj_set in filter_set.objectSet:
                    task = obj_set.obj
                    for change in obj_set.changeSet:
                        if change.name == 'info':
                            state = change.val.state
                        elif change.name == 'info.state':
                            state = change.val
                        else:
                            continue

                        if not str(task) in task_list:
                            continue

                        if state == vim.TaskInfo.State.success:
                            # Remove task from taskList
                            task_list.remove(str(task))
                        elif state == vim.TaskInfo.State.error:
                            raise task.info.error
            # Move to next version
            version = update.version
    finally:
        if pcfilter:
            pcfilter.Destroy()


def get_obj(content, vimtype, name):
    obj = None
    container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
    for c in container.view:
        if name:
            if c.name == name:
                obj = c
                break
            else:
                obj = c
    return obj


def update_virtual_nic_state(si, vm_obj, nic_number, new_nic_state):
    nic_prefix_label = '网络适配器 '
    nic_label = nic_prefix_label + str(nic_number)
    virtual_nic_device = None
    for dev in vm_obj.config.hardware.device:
        if isinstance(dev, vim.vm.device.VirtualEthernetCard) \
                and dev.deviceInfo.label == nic_label:
            virtual_nic_device = dev
    if not virtual_nic_device:
        raise RuntimeError('Virtual {} could not be found.'.format(nic_label))
    virtual_nic_spec = vim.vm.device.VirtualDeviceSpec()
    virtual_nic_spec.operation = \
        vim.vm.device.VirtualDeviceSpec.Operation.remove \
            if new_nic_state == 'delete' \
            else vim.vm.device.VirtualDeviceSpec.Operation.edit
    virtual_nic_spec.device = virtual_nic_device
    virtual_nic_spec.device.key = virtual_nic_device.key
    virtual_nic_spec.device.macAddress = virtual_nic_device.macAddress
    virtual_nic_spec.device.backing = virtual_nic_device.backing
    virtual_nic_spec.device.wakeOnLanEnabled = virtual_nic_device.wakeOnLanEnabled
    connectable = vim.vm.device.VirtualDevice.ConnectInfo()
    if new_nic_state == 'connect':
        connectable.connected = True
        connectable.startConnected = True
    elif new_nic_state == 'disconnect':
        connectable.connected = False
        connectable.startConnected = False
    else:
        connectable = virtual_nic_device.connectable
    virtual_nic_spec.device.connectable = connectable
    dev_changes = [virtual_nic_spec]
    spec = vim.vm.ConfigSpec()
    spec.deviceChange = dev_changes
    task = vm_obj.ReconfigVM_Task(spec=spec)
    wait_for_tasks(si, [task])
    return True


def disconnect(si):
    try:
        content = si.RetrieveContent()
        content.sessionManager.Logout()
    except Exception as e:
        pass


def change_vm_nic_state(host, user, password, vm_name, unit_number=1, nic_state="connect"):
    si = SmartConnect(host=host, user=user, pwd=password, port=443, disableSslCertValidation=True)
    content = si.RetrieveContent()
    print('Searching for VM {}'.format(vm_name))
    vm_obj = get_obj(content, [vim.VirtualMachine], vm_name)
    if vm_obj:
        print(si, vm_obj, unit_number, nic_state)
        update_virtual_nic_state(si, vm_obj, unit_number, nic_state)
        print('VM NIC {0} Successfully state changed to {1}'.format(unit_number, nic_state))
    else:
        print("VM not found")
    disconnect(si)


def join_out_list_fun(args):
    main_ip = filter_ip(args["ip_and_port_group"])
    # 纳管参数
    join_args = {}
    if join_args.get("resourceCode") is None:
        join_args["resourceCode"] = "linux"

    if join_args.get("managerIp") is None:
        join_args["managerIp"] = main_ip

    # 是否更新snc-agent配置
    if join_args.get("updateAgentConfig") is None:
        join_args["updateAgentConfig"] = False

    # 是否加密
    if join_args.get("needDecrypt") is None:
        join_args["needDecrypt"] = False

    if join_args.get("resourceGroupNames") is None:
        join_args["resourceGroupNames"] = ["SNC"]
    elif isinstance(join_args.get("resourceGroupNames"), list) and len(
            join_args.get("resourceGroupNames")) == 0:
        join_args["resourceGroupNames"].append("SNC")

    if join_args.get("templateHosts") is None:
        join_args["templateHosts"] = ["Host_Linux_Base_SncAgentScript"]
    elif isinstance(join_args.get("templateHosts"), list) and len(join_args.get("templateHosts")) == 0:
        join_args["templateHosts"].append("Host_Linux_Base_SncAgentScript")

    if join_args.get("attributes") is None:
        join_args["attributes"] = [{"code": "name", "value": main_ip}, {"code": "manager_ip", "value": main_ip},
                                   {"code": "sys_ip", "value": main_ip}]

    if join_args.get("proxyName") is None:
        join_args["proxyName"] = args["proxyName"]

    if join_args.get("extendedParams") is None:
        cert_str = '{"certificate":{"accessTypes":"ssh","username":"{ssh_username}","password":"{ssh_password}","port":"{ssh_port}","groupIds":[1]}}'
        cert_attr = json.loads(cert_str)
        # cert_attr["certificate"]["username"] = "shsnc"
        # cert_attr["certificate"]["password"] = "shsnc!@#"
        # cert_attr["certificate"]["port"] = "22"
        cert_attr["certificate"]["username"] = agent_user
        cert_attr["certificate"]["password"] = agent_user_pwd
        cert_attr["certificate"]["port"] = "22"
        join_args["extendedParams"] = cert_attr

    return join_args


def filter_ip(old_ip_list):
    # print(old_ip_list)
    # 过滤网段 196.*|80.*|127.*|172.*|80.*
    # old_ip_list = ip.split(",")
    new_ip_list = []
    for li in old_ip_list:
        ip = li["ip"]
        if ip.startswith("196.") or ip.startswith("80.") or ip.startswith("127.") \
                or ip.startswith("172.") or ip.startswith("193.") or len(ip.split(":")) == 8:
            continue
        new_ip_list.append(ip)
    return_ip = ""
    # 如果有1个IP，或大于2个IP, 则返回第一个网卡IP
    if len(new_ip_list) == 1 or len(new_ip_list) > 2:
        return_ip = new_ip_list[0]
    # 如果有2个IP, 则IP比大小，小的返回
    if len(new_ip_list) == 2:
        one_ip = int(new_ip_list[0].replace('.', ''))
        two_ip = int(new_ip_list[1].replace('.', ''))
        if one_ip < two_ip:
            return_ip = new_ip_list[0]
        else:
            return_ip = new_ip_list[1]
    # print(return_ip)
    return return_ip


def clone_vm():
    # 纳管数据出参数组
    join_out_list = list()
    create_stat_list = list()

    data_path = '/tmp/.ansible_vmware'
    file_name = 'clone_vm.yml'
    init_yaml_template(data_path, file_name, "clone")
    for args in in_parameter_json:
        if "vCenter" in args["type"]:
            update_clone_vm_yaml_data(data_path, file_name, args)

            print("Start Clone VM instance, please wait...")
            # quiet=True 表示安静地输出 | quiet=False 输出详细信息
            r = ansible_runner.run(quiet=False, private_data_dir=data_path, playbook=file_name)
            # print("{}: {}".format(r.status, r.rc))
            instance_status_dict = dict()
            instance_status_dict["instance_name"] = args["name"]
            instance_status_dict["instance_ip"] = filter_ip(args["ip_and_port_group"])
            if r.status in "successful" and str(r.rc) in "0":
                print("Create VM Successful")
                instance_status_dict["create_status"] = "success"
                join_out_list.append(join_out_list_fun(args))
                args["create_status"] = True
            else:
                exit("Create VM Failed")
                instance_status_dict["create_status"] = "fail"
                args["create_status"] = False
            create_stat_list.append(instance_status_dict)

            # # Get vm info
            # cache_file = "{0}/vm_cache.json".format(data_path)
            # if os.path.exists(cache_file):
            #     result_json = json_read(cache_file)
            #     instance = result_json["instance"]
            #     print("VM Name: {0}".format(instance["hw_name"]))
            #     print("VM Status: {0}".format(instance["hw_power_status"]))

            # 启动网卡
            if args["create_status"]:
                vm_name = "{0}_{1}".format(args["name"], filter_ip(args["ip_and_port_group"]))
                if len(args["ip_and_port_group"]) == 1:
                    change_vm_nic_state(vc_host, vc_username, vc_password, vm_name, 1)
                elif len(args["ip_and_port_group"]) == 2:
                    change_vm_nic_state(vc_host, vc_username, vc_password, vm_name, 1)
                    change_vm_nic_state(vc_host, vc_username, vc_password, vm_name, 2)
                time.sleep(3)
        else:
            print("Type Error")

    join_res = json.dumps(join_out_list)
    join_res = "resourceJoin" + join_res
    create_stat = json.dumps(create_stat_list)
    return join_res, create_stat


def update_ip():
    data_path = '/tmp/.ansible_vmware'
    file_name = 'update_ip.yml'
    init_yaml_template(data_path, file_name, "ip")
    for args in in_parameter_json:
        if "vCenter" in args["type"] and args["create_status"]:
            time.sleep(6)
            update_ip_yaml_data(data_path, file_name, args)

            print("Start modify IP, please wait...")
            # quiet=True 表示安静地输出 | quiet=False 输出详细信息
            r = ansible_runner.run(quiet=False, private_data_dir=data_path, playbook=file_name)
            # print("{}: {}".format(r.status, r.rc))
            if r.status in "successful" and str(r.rc) in "0":
                print("Modify IP Successful")
            else:
                print("Modify IP Failed, Retry ...")
                time.sleep(1)
                # 重试一次
                # r = ansible_runner.run(quiet=True, private_data_dir=data_path, playbook=file_name)
                # # print("{}: {}".format(r.status, r.rc))
                # if r.status in "successful" and str(r.rc) in "0":
                #     print("Modify IP Successful")
                # else:
                #     print("Modify IP Failed")

            # Get vm info
            cache_file = "{0}/vm_cache.json".format(data_path)
            if os.path.exists(cache_file):
                result_json = json_read(cache_file)
                instance = result_json["instance"]
                print("VM Name: {0}".format(instance["hw_name"]))
                print("VM Status: {0}".format(instance["hw_power_status"]))


if __name__ == '__main__':
    in_parameter = add_proxy(in_parameter.strip())
    in_parameter_json = json.loads(in_parameter.strip())
    join_result, create_status = clone_vm()
    update_ip()
    print('join_result:{}'.format(join_result))
    print('create_status:{}'.format(create_status))

    print("#####SNC PARAM SPAN#####join_result#snc#")
    print('{0}:{1}'.format('text', str(join_result)))
    print("#####SNC PARAM SPAN#####create_status#snc#")
    print('{0}:{1}'.format('text', str(create_status)))
    sys.exit(0)
